package com.xh.cdp.sys.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import com.xh.cdp.common.BaseDao;
import com.xh.cdp.common.EasyUIPageModel;
import com.xh.cdp.sys.dao.SysRoleDao;
import com.xh.cdp.sys.entity.SysRoleEntity;
import com.xh.cdp.sys.entity.SysUserEntity;

@Repository
public class SysRoleDaoImpl extends BaseDao<SysRoleEntity, String> implements SysRoleDao {

	@Override
	public List<SysRoleEntity> listUserRoleCombobox(String cate) {
		if("all".equals(cate))
			return listEntityByHql("FROM SysRoleEntity");
		return listEntityByHql("FROM SysRoleEntity WHERE id != 'sr-000'");
	}

	@Override
	public EasyUIPageModel<SysRoleEntity> listRole(String sort, String order, int page, int rows) {
		String hql = "FROM SysRoleEntity WHERE state = 1 AND id != 'sr-000'";
		return pageEntityByHqlEasyUI(page, rows, hql);
	}

	@Override
	public String addRole(SysRoleEntity role) {
		return save(role);
	}

	@Override
	public SysRoleEntity showRoleInfo(String id) {
		String hql = "FROM SysRoleEntity WHERE id = ?";
		return uniqueEntityByHql(hql, id);
	}

	@Override
	public Integer updateRoleState(SysRoleEntity role) {
		SysRoleEntity oldRole = get(role.getId());
		oldRole.setState(3 - role.getState());
		update(oldRole);
		return 1;
	}

	@Override
	public String updateRole(SysRoleEntity role) {
		SysRoleEntity oldRole = get(role.getId());
		if(oldRole != null) {
			oldRole.setName(role.getName());
			oldRole.setState(role.getState());
		}
		return save(oldRole);
	}

	@Override
	public Integer deleteRole(String ids) {
		String hql = "UPDATE SysRoleEntity SET state = 2 WHERE id IN (:ids)";
		Integer row = getSession().createQuery(hql).setParameterList("ids", ids.split(",")).executeUpdate();
		return row;
	}

	@Override
	public EasyUIPageModel<SysRoleEntity> listRoleBySearch(String sort, String order, Integer page, Integer rows,
			String searchName, Integer state) {
		List<Object> paramList = new ArrayList<>();
		StringBuilder sb = new StringBuilder();
		sb.append("FROM SysRoleEntity ");
		sb.append("WHERE id != 'sr-000' ");
		if(state != -1) {
			sb.append("AND state = ? ");
			paramList.add(state);
		}	
		if (StringUtils.isNotBlank(searchName)) {
			sb.append("AND name LIKE ? ");
			paramList.add("%" + searchName + "%");
		}
		return pageEntityByHqlEasyUI(page, rows, sb.toString(), paramList);
	}

}
